//
//  OAuthViewController.swift
//  YYWeiBo
//
//  Created by 崔洋洋 on 15/10/10.
//  Copyright © 2015年 崔洋洋. All rights reserved.
//


import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController, UIWebViewDelegate {
    
    // MARK: 界面加载
    private lazy var webView = UIWebView()
    override func loadView() {
        view = webView
        webView.delegate = self
        title = "YY微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    // 关闭页面
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 加载授权页面
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthUrl()))
        
    }
    
    // MARK: 代理UIWebViewDelegate
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
        print("开始")
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
        print("结束")
    }
    
    /*
    如果请求的 URL 包含回调地址,需要判断参数,否则继续加载
    若果请求参数中包含 code 可以从请求的 URL 中获得请求码
    */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        
        // 判断是否包含回调地址
        if !urlString.hasPrefix(NetworkTools.sharedTools.redirectUri) {
            return true
        }
        print("判断参数")
        print(request.URL?.query)
        
        if let query = request.URL?.query where query.hasPrefix("code=") {
            print("获取授权码")
            
        // 从 query中街区授权码
          let code = query.substringFromIndex("code=".characters.endIndex)
            print(code)
            
            // TODO: 换取 token
            loadAccessToken(code)
            
        }else {
            close()
        }
        
        return false
        
    }
    private func loadAccessToken(code: String) {
        NetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil || result == nil {
                SVProgressHUD.showInfoWithStatus("您的网络不给力呦")
                // 延时关闭
                let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
                dispatch_after(when, dispatch_get_main_queue()) {
                    self.close()
                }
                
                return
            }
            print(result)
            
            // 字典转模型
            let account = UserAccount(dict: result!)
            print(account)
        }
    }
}